<?php

namespace app\api\model;

use app\api\model\store\Shop;
use app\api\model\store\ShopActivation;
use think\Cache;
use app\common\library\wechat\WxUser;
use app\common\exception\BaseException;
use app\common\model\User as UserModel;
use app\api\model\dealer\Referee as RefereeModel;
use app\api\model\dealer\Setting as DealerSettingModel;
use Yurun\OAuthLogin\Weixin\OAuth2;
use think\Session;
/**
 * 用户模型类
 * Class User
 * @package app\api\model
 */
class User extends UserModel
{
    private $token;

    /**
     * 隐藏字段
     * @var array
     */
    protected $hidden = [
        'open_id',
        'is_delete',
        'wxapp_id',
        'create_time',
        'update_time'
    ];

    /**
     * 获取用户信息
     * @param $token
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function getUser($token)
    {
        $openId = Cache::get($token)['openid'];
        return self::detail(['open_id' => $openId], ['address', 'addressDefault', 'grade']);
    }

    /**
     * 获取登录验证二维码地址
     */
    public function getqrurl(){
        // 获取当前程序信息
        $wxConfig = Wxapp::getWxappCache();
        $callbackurl = base_url().url('api/user/checklogin',['wxapp_id'=>self::$wxapp_id]);
        $oauth2 = new OAuth2($wxConfig['app_id'],$wxConfig['app_secret'],$callbackurl);
        $url = $oauth2->getAuthUrl();
//        echo $url;
//        echo "<br>";
//        echo self::$wxapp_id;
//        echo "<br>";
//        echo $oauth2->state;
//        exit();
        Session::set('YURUN_WX_STATE'.self::$wxapp_id,$oauth2->state);
        return $url;
    }

    /**
     * @param $post
     */
    public function tlogin($post){
        $openid = $post['open_id'];
        // 自动注册用户
        $refereeId = null;
        $userInfo['nickName'] = 'test';
        $userInfo['gender'] = 1;
        $userInfo['country'] = '中国';
        $userInfo['province'] = '山西';
        $userInfo['city'] = '太原';
        $userInfo['avatarUrl'] = 'aaaa/aaa';
        $user_id = $this->register($openid, $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($openid);
        $sesson['openid'] = $openid;
        // 记录缓存, 7天
        Cache::set($this->token, $sesson, 86400 * 7);
        return $user_id;
    }

    /**
     * 激活使用账号
     * @param $post
     * @param $user_id
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function activation($post,$user_id){
        //验证字段是否完整
        if (!$this->validatefrom($post)){
            return false;
        }
        //查询对应的培训机构配额是否已经使用完
        $shop = Shop::where('shop_id','=',$post['shop_id'])
            ->where('is_delete','=',0)
            ->find();
        if (!$shop){
            $this->error = '未获取到机构编号对应的数据';
            return false;
        }
        if ($shop->status == 0){
            $this->error = '机构已被禁用';
            return false;
        }
        //
        $is_activation = ShopActivation::where('shop_id','=',$post['shop_id'])
            ->where('user_id','=',$user_id)
            ->count();
        if ($is_activation){
            $this->error = '您已激活该机构';
            return false;
        }
        //获取对应机构已激活数量
        $activation_num = ShopActivation::where('shop_id','=',$post['shop_id'])->count();
        if (($activation_num > $shop->active_num) || ($activation_num == $shop->active_num)){
            $this->error = '机构可激活使用数量已满';
            return false;
        }
        //查询秘钥是否正确
        if($post['password'] != $shop->password){
            $this->error = '激活码错误';
            return false;
        }
        //存入激活记录
        $data['user_id'] = $user_id;
        $data['shop_id'] = $post['shop_id'];
        $data['wxapp_id'] = self::$wxapp_id;
        $shopactmodel = new ShopActivation();
        if ($shopactmodel->save($data)){
            return true;
        }else{
            $this->error = '激活失败';
            return false;
        }

    }
    /**
     * 用户登录
     * @param array $post
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function login($post)
    {
        // 微信登录 获取session_key
        $session = $this->wxlogin($post['code']);
        // 自动注册用户
        $refereeId = isset($post['referee_id']) ? $post['referee_id'] : null;
        $userInfo = json_decode(htmlspecialchars_decode($post['user_info']), true);
        $user_id = $this->register($session['openid'], $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($session['openid']);
        // 记录缓存, 7天
        Cache::set($this->token, $session, 86400 * 7);
        return $user_id;
    }
    /**
     * 新-用户登录
     * @param array $data
     * @return string
     * @throws BaseException
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function lessonlogin($data)
    {
        // 微信登录 获取session_key
        $openid = $data['openid'];
        $userInfo['nickName'] = $data['nickname'];
        $userInfo['gender'] = $data['sex'];
        $userInfo['country'] = $data['country'];
        $userInfo['province'] = $data['province'];
        $userInfo['city'] = $data['city'];
        $userInfo['avatarUrl'] = $data['headimgurl'];
        // 自动注册用户
        $refereeId = null;
        $user_id = $this->register($openid, $userInfo, $refereeId);
        // 生成token (session3rd)
        $this->token = $this->token($openid);
        $sesson['openid'] = $openid;
        // 记录缓存, 7天
        Cache::set($this->token, $sesson, 86400 * 7);
        return $user_id;
    }

    /**
     * 对应的用户是否有激活记录
     * @param $user_id
     * @return array|bool|float|int|mixed|object|\stdClass|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function hasActivation($user_id){
        $model = ShopActivation::where('user_id','=',$user_id)->find();
        return $model;
    }

    /**
     * @param $user_id
     * @return int  0未过期  1已过期
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function isEndtime($user_id){
        $shopmodel = ShopActivation::where('user_id','=',$user_id)->find();
        if (!$shopmodel){
            return 0;
        }else{
            $shop_id = $shopmodel['shop_id'];
            $shop = Shop::where('shop_id','=',$shop_id)->find();
            if (!$shop){
                return 0;
            }else{
                $endtime = strtotime($shop['endtime']);
                if (!$endtime){
                    return 0;
                }else{
                    return $endtime>time()?0:1;
                }
            }
        }
    }
    /**
     * 获取token
     * @return mixed
     */
    public function getToken()
    {
        return $this->token;
    }


    /**
     * 微信登录
     * @param $code
     * @return array|mixed
     * @throws BaseException
     * @throws \think\exception\DbException
     */
    private function wxlogin($code)
    {
        // 获取当前小程序信息
        $wxConfig = Wxapp::getWxappCache();
        // 验证appid和appsecret是否填写
        if (empty($wxConfig['app_id']) || empty($wxConfig['app_secret'])) {
            throw new BaseException(['msg' => '请到 [后台-微信登录管理] 填写appid 和 appsecret']);
        }
        // 微信登录 (获取session_key)
        $WxUser = new WxUser($wxConfig['app_id'], $wxConfig['app_secret']);
        if (!$session = $WxUser->sessionKey($code)) {
            throw new BaseException(['msg' => $WxUser->getError()]);
        }
        return $session;
    }

    /**
     * 生成用户认证的token
     * @param $openid
     * @return string
     */
    private function token($openid)
    {
        $wxapp_id = self::$wxapp_id;
        // 生成一个不会重复的随机字符串
        $guid = \getGuidV4();
        // 当前时间戳 (精确到毫秒)
        $timeStamp = microtime(true);
        // 自定义一个盐
        $salt = 'token_salt';
        return md5("{$wxapp_id}_{$timeStamp}_{$openid}_{$guid}_{$salt}");
    }

    /**
     * 自动注册用户
     * @param $open_id
     * @param $data
     * @param int $refereeId
     * @return mixed
     * @throws \Exception
     * @throws \think\exception\DbException
     */
    private function register($open_id, $data, $refereeId = null)
    {

        // 查询用户是否已存在
        $user = self::detail(['open_id' => $open_id]);
        $model = $user ?: $this;
        if ($user){
            return $user['user_id'];
        }
        $this->startTrans();
        try {
            // 保存/更新用户记录
            if (!$model->allowField(true)->save(array_merge($data, [
                'open_id' => $open_id,
                'wxapp_id' => self::$wxapp_id
            ]))) {
                throw new BaseException(['msg' => '用户注册失败']);
            }
            // 记录推荐人关系
            if (!$user && $refereeId > 0) {
                RefereeModel::createRelation($model['user_id'], $refereeId);
            }
            $this->commit();
        } catch (\Exception $e) {
            $this->rollback();
            throw new BaseException(['msg' => $e->getMessage()]);
        }
        return $model['user_id'];
    }

    /**
     * 个人中心菜单列表
     * @return array
     */
    public function getMenus()
    {
        $menus = [
            'address' => [
                'name' => '收货地址',
                'url' => 'pages/address/index',
                'icon' => 'map'
            ],
            'coupon' => [
                'name' => '领券中心',
                'url' => 'pages/coupon/coupon',
                'icon' => 'lingquan'
            ],
            'my_coupon' => [
                'name' => '我的优惠券',
                'url' => 'pages/user/coupon/coupon',
                'icon' => 'youhuiquan'
            ],
            'sharing_order' => [
                'name' => '拼团订单',
                'url' => 'pages/sharing/order/index',
                'icon' => 'pintuan'
            ],
            'my_bargain' => [
                'name' => '我的砍价',
                'url' => 'pages/bargain/index/index?tab=1',
                'icon' => 'kanjia'
            ],
            'dealer' => [
                'name' => '分销中心',
                'url' => 'pages/dealer/index/index',
                'icon' => 'fenxiaozhongxin'
            ],
            'help' => [
                'name' => '我的帮助',
                'url' => 'pages/user/help/index',
                'icon' => 'help'
            ],
        ];
        // 判断分销功能是否开启
        if (DealerSettingModel::isOpen()) {
            $menus['dealer']['name'] = DealerSettingModel::getDealerTitle();
        } else {
            unset($menus['dealer']);
        }
        return $menus;
    }

    /**
     * @param $param
     */
    private function validatefrom($param){
        if (empty($param['shop_id'])) {
            $this->error = '机构编号未填写';
            return false;
        }
        if (empty($param['password'])) {
            $this->error = '机构激活秘钥未填写';
            return false;
        }
        return true;
    }

    /**
     * 根据用户token 获取对应机构信息
     * @param $userInfo
     * @return array|bool|false|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getStore($userInfo){
        $user_id = $userInfo['user_id'];
        $shop = ShopActivation::where('user_id','=',$user_id)->find();
        $shopinfo = Shop::with('logo')->find($shop['shop_id']);
        return $shopinfo;
    }
}
